package com.luzhikun.charator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决中文乱码问题
 */
public class CharactorEncoding extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 解决了POST请求的中文乱码问题，其解决不了GET请求中的乱码问题  因为GET请求在请求头中
        // setCharacterEncoding()方法设置了请求正文中的字符编
        // req.setCharacterEncoding("UTF-8");

        // 同时解决POST请求方式和GET请求方式的乱码问题
        // 这里获取的name1 字符集是 ISO8859-1
        String name1 = req.getParameter("name");
        // 将name字符串 按照原编码进行打散
        byte[] bytes = name1.getBytes("ISO8859-1");
        // 将bytes字节数组按照指定字符编码进行组装为String
        name1 = new String(bytes, "UTF-8");


        // 获取指定参数的值
        String name = req.getParameter("name");
        // POST 请求时：é???????¤
        System.out.println(name);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
